<template>
  <a-modal
    :title="title"
    :width="1200"
    :ok=false
    :visible="visible"
    :confirmLoading="confirmLoading"
    :okButtonProps="{ props: {disabled: disableSubmit} }"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-row>
          <a-col :span="24">
          <a-card title="部门信息" style="width: 100%">
          <a-col :span="12" v-if="!model.id && model.orgCategory=='20'">
            <a-form-model-item  label="选择角色" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="roleId">
              <j-dict-select-tag type="list" v-model="model.roleId" dictCode="sys_role,role_name,id" dict-where="role_type=1 order by role_code asc" placeholder="请选择角色" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="部门名称"
              prop="departName"
              :hidden="false"
              hasFeedback >
              <a-input id="departName" placeholder="请输入部门名称" v-model="model.departName"/>
            </a-form-model-item>
          </a-col>
            <a-col :span="12" >
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                prop="level"
                label="部门类型">
                <template v-if="seen">
                  <a-radio-group v-model="model.level" placeholder="请选择部门类型">
                    <a-radio value="0">
                      店铺
                    </a-radio>
                  </a-radio-group>
                </template >
                <template v-if="!seen">
                  <a-radio-group v-model="model.level" placeholder="请选择部门类型">
                    <a-radio value="1">
                      运营部门
                    </a-radio>
                  </a-radio-group>
                </template>
              </a-form-model-item>
            </a-col>

          <a-col :span="12"  :hidden="seen">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="上级部门" hasFeedback>
            <a-tree-select
              style="width:100%"
              :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
              :treeData="departTree"
              v-model="model.parentId"
              placeholder="请选择上级部门"
              :disabled="condition">
            </a-tree-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="mobile"
              label="联系电话">
              <a-input placeholder="联系电话" v-model="model.mobile"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="联系地址">
              <a-input placeholder="联系地址" v-model="model.address"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="位置排序">
              <a-input-number v-model="model.departOrder" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
            <a-col v-if="parentLevel===300" :span="12">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="关联银行">
                <j-select-depart-work v-model="model.bankOrgCode" org-code="A08A03"  title="银行" store="orgCode" :parentDisabled="true" />
              </a-form-model-item>
            </a-col>

          <a-col :span="12" >
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="备注信息">
              <a-textarea placeholder="请输入备注信息" v-model="model.memo"/>
            </a-form-model-item>
          </a-col>
          </a-card>
          </a-col>
          <a-col :span="24" v-if="!model.id && model.orgCategory=='20'" style="margin-top: 15px;">
            <a-card title="管理员账号" style="width: 100%">
              <!--<template #extra><a href="#">more</a></template>-->
              <a-col :span="12" >
                <a-form-model-item label="登录账号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="username">
                  <a-input placeholder="请输入登录账号" v-model="model.username" :readOnly="!!model.id"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="12" >
                <a-form-model-item label="管理员名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="realname">
                  <a-input placeholder="请输入管理员名称" v-model="model.realname" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12" >
                <a-form-model-item label="登录密码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="password" >
                  <a-input type="password" placeholder="请输入登录密码" v-model="model.password" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12" >
                <a-form-model-item label="确认密码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="confirmpassword" >
                  <a-input type="password" @blur="handleConfirmBlur" placeholder="请重新输入登录密码" v-model="model.confirmpassword"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="12" >
              <a-form-model-item label="联系地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="address">
                <a-input placeholder="请输入联系地址" v-model="model.address" />
              </a-form-model-item>
              </a-col>
              <a-col :span="12" >
              <a-form-model-item label="手机号码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="phone">
                <a-input placeholder="请输入手机号码" v-model="model.phone" />
              </a-form-model-item>
              </a-col>
            </a-card>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
  import { httpAction } from '@/api/manage'
  import { queryIdTree } from '@/api/api'
  import pick from 'lodash.pick'
  import ATextarea from 'ant-design-vue/es/input/TextArea'
  import { duplicateCheck } from '@/api/api'
  import moment from "moment";
  export default {
    name: "SysDepartModal",
    components: { ATextarea },
    data () {
      return {
        confirmDirty: false,
        userId:"", //保存用户id
        departTree:[],
        orgTypeData:[],
        phoneWarning:'',
        departName:"",
        title:"操作",
        seen:false,
        visible: false,
        condition:true,
        disableSubmit:false,
        model: {},
        parentLevel:'',
        defaultModel:{
          departOrder:0,
          orgCategory:'20'
        },
        menuhidden:false,
        menuusing:true,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        validatorRules:{
          departName:[{ required: true, message: '请输入部门名称!' }],
          roleId:[{ required: true, message: '请输选择所属角色!' }],
          orgCode:[{ required: true, message: '请输入部门编码!' }],
          mobile: [{validator:this.validateMobile}],
          orgCategory:[{required: true, message: '请输入部门类型!'}],
          level:[{required: true, message: '请输入部门类型!'}],
          username:[{required: true, message: '请输入用户账号!'},
            {validator: this.validateUsername,}],
          password: [{required: true,pattern:/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/,message: '密码由8位数字、大小写字母和特殊符号组成!'},
            {validator: this.validateToNextPassword,trigger: 'change'}],
          confirmpassword: [{required: true, message: '请重新输入登录密码!',},
            { validator: this.compareToFirstPassword,}],
          realname:[{ required: true, message: '请输入用户名称!' }],
          phone: [{required: true, message: '请输入手机号!'}],
        },
        url: {
          add: "/sys/sysDepart/add",
        },
        dictDisabled:true,
      }
    },
    created () {



    },
    methods: {
      loadTreeData(){
        var that = this;
        queryIdTree().then((res)=>{
          if(res.success){
            that.departTree = [];
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i];
              that.departTree.push(temp);
            }
          }

        })
      },
      add (depart) {
        if(depart){
          this.seen = false;
          this.dictDisabled = false;
        }else{
          this.parentLevel = '';
          this.seen = true;
          this.dictDisabled = true;
        }
        this.edit(depart);
      },
      edit (record) {
          this.visible = true;
          this.model = Object.assign({}, this.defaultModel, record)
          this.loadTreeData();
          this.model.parentId = record!=null?record.toString():null;
           if(this.seen){
             this.model.orgCategory = '20';
           }else{
             this.model.orgCategory = '21';
           }
      },
      close () {
        this.$emit('close');
        this.disableSubmit = false;
        this.visible = false;
        this.$refs.form.resetFields();
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            if(undefined != this.model.username && '' != this.model.username){
              this.model.sysUser = {
                userIdentity:2,
                loginOnly:1,
                type:2,
                username:this.model.username,
                password:this.model.password,
                realname:this.model.realname,
                address:this.model.address,
                phone:this.model.phone,
              };
            }else{
              this.model.sysUser = null;
            }
            httpAction(this.url.add,this.model,"post").then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.loadTreeData();
                that.$emit('ok');
                that.close();
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })

          }else{
            return false;
          }
        })
      },
      handleCancel () {
        this.close()
      },
      validateMobile(rule,value,callback){
        if (!value || new RegExp(/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/).test(value)){
          callback();
        }else{
          callback("您的手机号码格式不正确!");
        }

      },
      handleConfirmBlur(e) {
        const value = e.target.value;
        this.confirmDirty = this.confirmDirty || !!value
      },
      validateUsername(rule, value, callback){
        var params = {
          tableName: 'sys_user',
          fieldName: 'username',
          fieldVal: value,
          dataId: this.userId,
         // ruleOut:"del_flag = 0"
        };
        duplicateCheck(params).then((res) => {
          if (res.success) {
            callback()
          } else {
            callback("用户名已存在!")
          }
        })
      },
      validateToNextPassword (rule, value, callback) {
        const confirmpassword=this.model.confirmpassword;
        if (value && confirmpassword && value !== confirmpassword) {
          callback('两次输入的密码不一样！');
        }
        if (value && this.confirmDirty) {
          this.$refs.form.validateField(['confirmpassword']);
        }
        callback();
      },
      compareToFirstPassword (rule, value, callback) {
        if (value && value !== this.model.password) {
          callback('两次输入的密码不一样！');
        } else {
          callback()
        }
      },
      validatePhone(rule, value, callback){
        if(!value){
          callback()
        }else{
          if(new RegExp(/^1[3|4|5|7|8|9][0-9]\d{8}$/).test(value)){
            var params = {
              tableName: 'sys_user',
              fieldName: 'phone',
              fieldVal: value,
              dataId: this.userId,
             // ruleOut:"del_flag = 0"
            };
            duplicateCheck(params).then((res) => {
              if (res.success) {
                callback()
              } else {
                callback("手机号已存在!")
              }
            })
          }else{
            callback("请输入正确格式的手机号码!");
          }
        }
      },
    }
  }
</script>

<style scoped>

</style>